import { AuthState } from '@/store/modules/auth/types'
import { ActionContext, createStore, Store, useStore as baseUseStore } from 'vuex'
import { login } from '@/api/chunfeng/auth'
import { App, InjectionKey } from 'vue'
import { useAuthTool } from '@/utils/auth'

const { removeAuthToken, setAuthToken } = useAuthTool()

const state: AuthState = {
  token: undefined,
  expired: undefined
}

const mutations = {
  setToken: (state: AuthState, payload: { token: string; expired: Date }): void => {
    state.token = payload.token
    state.expired = payload.expired
  },

  resetToken: (state: AuthState): void => {
    state.token = undefined
    state.expired = undefined
  }
}

const actions = {
  login({ commit }: ActionContext<AuthState, AuthState>, userInfo): Promise<any> {
    return new Promise<void>((resolve, reject) => {
      login(userInfo)
        .then((tokenResult) => {
          commit('setToken', tokenResult.value)
          setAuthToken(tokenResult.value)
          resolve()
        })
        .catch((status) => {
          reject(status)
        })
    })
  },
  resetToken({ commit }: ActionContext<AuthState, AuthState>): Promise<any> {
    return new Promise<void>((resolve) => {
      commit('resetToken')
      removeAuthToken()
      resolve()
    })
  }
}

const authKey: InjectionKey<Store<AuthState>> = Symbol()
const store = createStore<AuthState>({
  state,
  mutations,
  actions
})

export function useAuthStore(): Store<AuthState> {
  return baseUseStore(authKey) || store
}

export function install(app: App) {
  app.use(store, authKey)
}
